package com.xnx3.banmahuishou.userApplet.controller;

import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sun.tools.javac.resources.javac;
import com.xnx3.DateUtil;
import com.xnx3.IntegerUtil;
import com.xnx3.banmahuishou.core.entity.LotteryRecord;
import com.xnx3.banmahuishou.core.entity.LuckDrawPrize;
import com.xnx3.banmahuishou.core.entity.ScoreChangeRecord;
import com.xnx3.banmahuishou.userApplet.vo.ChoujiangInfoVO;
import com.xnx3.banmahuishou.userApplet.vo.PrizeListVO;
import com.xnx3.j2ee.controller.BaseController;
import com.xnx3.j2ee.entity.System;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.wangmarket.shop.core.entity.Order;

/**
 * 抽奖转盘相关
 * @author zxy
 */
@Controller(value="BanmahuishouUserAppletPrizeController")
@RequestMapping("/userApplet/prize/")
public class PrizeController extends BaseController{
	@Resource
	private SqlService sqlService;
	/**
	 * 奖品列表
	 */
	@RequestMapping(value="getPrizeList.json",method = {RequestMethod.POST})
	@ResponseBody
	public PrizeListVO getPrizeList(HttpServletRequest request) {
		//奖品信息VO
		PrizeListVO vo = new PrizeListVO();
		String sqlString = "SELECT * FROM laji_luck_draw_prize";
		List<LuckDrawPrize> list = sqlService.findBySqlQuery(sqlString, LuckDrawPrize.class);
		//单笔订单获得抽奖次数的门槛  默认100元 
		int money = 100;
		String name = "LOTTERY_AMOUNT_SETTING";
		//将system表里对应的记录取出来
		System system = sqlService.findAloneByProperty(System.class, "name", name);
		// 如果记录存在 赋值给money
		if (system != null && system.getValue().length() != 0 ) {
			money = Integer.parseInt(system.getValue());
		}
		vo.setJine(Integer.toString(money));
		vo.setList(list);
		ActionLogUtil.insert(request, getUserId(), "获取奖品列表 :" + list.toString());
		return vo;
	}

	/**
	 * 进行抽奖 
	 * @return 返回抽中了什么
	 * @author 管雷鸣
	 */
	@RequestMapping(value="zhuanPanchoujiang.json" , method = RequestMethod.POST)
	@ResponseBody
	public ChoujiangInfoVO zhuanPanchoujiang(HttpServletRequest request){
		ChoujiangInfoVO vo = new ChoujiangInfoVO();
		int id = getUserId();
		User user = sqlService.findById(User.class,id);
		if(user == null){
			vo.setBaseVO(BaseVO.FAILURE, "用户信息获取失败");
			return vo;
		}
		String name = user.getNickname();
		int nowTime = DateUtil.timeForUnix10();
		//当天0点的时间戳
		int currentDayZeroTime = DateUtil.getDateZeroTime(nowTime);
		//第二天零点时间戳
		Integer dateNight = currentDayZeroTime + 86400;
		//查看用户抽过几次奖
		String sql = "SELECT * FROM laji_lottery_record WHERE userid=" + id 
				+ " AND add_time >=" + currentDayZeroTime + " AND add_time <" + dateNight;
		List<LotteryRecord> cishuList = sqlService.findBySqlQuery(sql, LotteryRecord.class);
		int cishu = cishuList.size();
		if(cishu >= 3){
			//已经抽了三次了，当前第四次，那肯定不让抽了
			vo.setBaseVO(BaseVO.FAILURE, "每日抽奖上限为三次，您已达到次数上限");
			return vo;
		}
		//现在有几次抽奖机会
		int havecishu = user.getLotteryDrawCount();
		if (havecishu <= 0) {
			vo.setBaseVO(BaseVO.FAILURE, "没有抽奖次数");
			return vo;
		}
		//判断当前用户当前是否还可以抽奖
		if (havecishu > 0) {
			vo.setChoujiangcishu(cishu + 1);
			ActionLogUtil.insert(request,id, "进行抽奖");
			List<LuckDrawPrize> list = sqlService.findAll(LuckDrawPrize.class);
			//总几率
			int count = 0;
			for (int i = 0; i < list.size(); i++) {
				LuckDrawPrize luckDrawPrize = list.get(i);
				count = count + luckDrawPrize.getPrizeProbability();
			}
			//随机取出一个奖品
			LuckDrawPrize trueDrawPrize = choujiang(count, list);
			if(trueDrawPrize != null){	
//				for (int i = 0; i < 50; i++) {
//					LuckDrawPrize trueDrawPrize = sqlService.findById(LuckDrawPrize.class, jiangpin.getId());
//					if(trueDrawPrize.getCount() < 1){
//						//输出语句 先注释掉 方便维护查看
//						ConsoleUtil.log("抽到的这个奖品没有库存了：" + trueDrawPrize.getPrizeName());
//						//没有奖品了，那么再抽一个
//						jiangpin = choujiang(count, list);
//					}else{
						//这个奖品可以用，那么跳出for循环，同时奖品数量-1 现在奖品只是积分 不做次数处理
						trueDrawPrize.setCount(trueDrawPrize.getCount() - 1);
						sqlService.save(trueDrawPrize);
						//用户抽奖次数减1
						user.setLotteryDrawCount(havecishu - 1);

						vo.setPrizeName(trueDrawPrize.getPrizeName());
						vo.setPrizeNum(trueDrawPrize.getPrizeNum());
						//创建抽奖记录
						LotteryRecord lotteryRecord = new LotteryRecord();
						lotteryRecord.setUserid(id);
						lotteryRecord.setAddTime(nowTime);
						lotteryRecord.setPrizeid(trueDrawPrize.getId());
						lotteryRecord.setPrizename(trueDrawPrize.getPrizeName());
						lotteryRecord.setNickname(name);
						sqlService.save(lotteryRecord);
						int jiangliNum = trueDrawPrize.getPrizeNum();
						//判断奖品的类型1: 积分, 2: 实际物品
						if( (trueDrawPrize.getType() - LuckDrawPrize.TYPE_INTEGRAL) == 0) {
							//创建积分变动记录
							ScoreChangeRecord scoreChangeRecord = new ScoreChangeRecord();
							scoreChangeRecord.setUserid(id);
							scoreChangeRecord.setAddTime(nowTime);
							scoreChangeRecord.setChangePoints(jiangliNum);
							scoreChangeRecord.setType(ScoreChangeRecord.TYPE_CHOUJIANG);
							scoreChangeRecord.setRemarks(DateUtil.intToString(nowTime, "yyyy-MM-dd HH:mm:ss") 
									+ name + "抽奖获得了" + jiangliNum +"积分,相关抽奖记录id为：" + lotteryRecord.getId());
							scoreChangeRecord.setTitle("抽奖获得积分");
							sqlService.save(scoreChangeRecord);
							//给用户积分余额加上邀请新用户获得的积分
							Integer currency = user.getCurrency() < 0 ? 0 : user.getCurrency();
							user.setCurrency(currency + jiangliNum);
							
						}else {
							//实物奖励 以后有的时候再添加
						}
						sqlService.save(user);
						//输出语句 先注释掉 方便维护查看
//						ConsoleUtil.log("抽到奖品："+trueDrawPrize.getPrizeName().toString());
//					}
//				}
			}
			if(trueDrawPrize == null){
				//异常
				vo.setBaseVO(BaseVO.FAILURE, "异常，请重新抽取");
				return vo;
			}
		}
		ActionLogUtil.insert(request, id, "进行抽奖");
		return vo;
	}

	/**
	 * 从奖品中随机抽一个奖品
	 * @param count 总的中奖几率
	 * @param list 奖品列表
	 * @return 如果返回null，则是没有随机获取到奖品
	 * @author 管雷鸣 
	 */
	private LuckDrawPrize choujiang(int count, List<LuckDrawPrize> list){
		//随机取一个数，看看是哪个奖项
		int rand = IntegerUtil.random(1, count);

		//中奖的奖品
		LuckDrawPrize zhongjiangAward = null;

		//看看随机数在哪个奖品区间。
		int numberplus = 0;
		for (int i = 0; i < list.size(); i++) {
			LuckDrawPrize luckDrawPrize = list.get(i);
			numberplus = numberplus + luckDrawPrize.getPrizeProbability();
			if(numberplus > rand){
				zhongjiangAward = luckDrawPrize;
				break;
			}
		}
		return zhongjiangAward;
	}

}
